package flights.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import flights.bi.Admin;

public class AdminHandler {
	public static Admin getUserByCredentials(String email, String password) throws SQLException
	{
		Admin admin_user = null;
		Connection conn = DBConn.createConnection();
		String sql = "SELECT * FROM tblemployees WHERE fldUserName=? and fldPassword=?";
		
		try (PreparedStatement st = conn.prepareStatement(sql)) {
			st.clearParameters();
			st.setString(1,email);
			st.setString(2,password);
			ResultSet rs = st.executeQuery();
			admin_user = extractAdminsFromRS(rs);
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}
		
		conn.close();
		return admin_user;
	}
	
	
	
	private static Admin extractAdminsFromRS(ResultSet ResultSet) throws SQLException {
		Admin admin = null;
		int nRowCount = 0;
		while (ResultSet.next()) {
			int admin_id = ResultSet.getInt("fldempid");
			String password = ResultSet.getString("fldpassword");
			String user_name = ResultSet.getString("fldusername");
			String first_name = ResultSet.getString("fldfname");
			String last_name = ResultSet.getString("fldlname");

			admin = new Admin(admin_id,password,user_name,first_name,last_name);
			nRowCount++;
		}
		
		if (nRowCount != 1)
		{
			return null;
		}
		
		return admin;
	}



	public static Admin getUserByID(int parsedInt) throws SQLException {
		Admin admin_user = null;
		Connection conn = DBConn.createConnection();
		String sql = "SELECT * FROM tblemployees WHERE fldempid = ?";
		
		try (PreparedStatement st = conn.prepareStatement(sql)) {
			st.clearParameters();
			st.setInt(1,parsedInt);
			ResultSet rs = st.executeQuery();
			admin_user = extractAdminsFromRS(rs);
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}
		
		conn.close();
		return admin_user;
	}

}
